package com.mjk.common.util;


import com.mjk.common.tools.logger.BizLogger;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Map;
import java.util.concurrent.*;

public class ThreadUtils {
	
	public static final ThreadLocal<Map<String,String>> local = new ThreadLocal<>();
	
	public static void sleep(long time){
		try{
			Thread.sleep(time);
		}catch(Exception e){
			BizLogger.error(e);
            Thread.currentThread().interrupt();
		}
	}
	/**
	 * 执行线程池，如果有异常，会再次执行
     */
	public static void excuteWithResult(Runnable run){
		ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
        ScheduledFuture<?> future = pool.schedule(run, 0, TimeUnit.MILLISECONDS);//pool.scheduleAtFixedRate(run, 0, 1000, TimeUnit.MILLISECONDS);
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            BizLogger.error(e.getMessage());
            excuteWithResult(run);
            Thread.currentThread().interrupt();
        }finally {
            pool.shutdown();
        }
	}
	
	public static void excuteWithNoResult(Runnable run){
		ExecutorService pool = Executors.newSingleThreadExecutor(new MyFactory(run));
		pool.execute(run);
		pool.shutdown();
	}

    private record MyFactory(Runnable task) implements ThreadFactory {
        @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setUncaughtExceptionHandler((t, e) -> {
                    BizLogger.info(e.getMessage());
                    ExecutorService pool = Executors.newSingleThreadExecutor(new MyFactory(task));
                    pool.execute(task);
                    pool.shutdown();
                });
                return thread;
            }
        }
}
